package export

import (
	"fmt"
	"os"
	"time"
)

func WriteToFile(name string, dataCH chan string, done chan bool) {
	var fileObj *os.File
	var err error
	fileObj, err = os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
	fmt.Printf("write file\t%s\tat\t%s\n", name, time.Now().Format("2006-01-02 15:04:05"))
	if err != nil {
		fmt.Println("Failed to open the file", err.Error())
		os.Exit(2)
	}
	defer func(fileObj *os.File) {
		err := fileObj.Close()
		if err != nil {
			fmt.Println(err)
		}
	}(fileObj)
	defer func() {
		done <- true
	}()
	i := 0
	for data := range dataCH {
		//fmt.Println("write has data", i)
		i++
		if _, err := fileObj.WriteString(data); err != nil {
			fmt.Println(err)
		}
	}
	fmt.Printf("write end\t \tat\t%s\n", time.Now().Format("2006-01-02 15:04:05"))

}
